import React from 'react'
import Component, { mapStateToProps, mapDispatchToProps } from '@components/Component'
import { connect } from 'react-redux'
import { Form, Row, Col, DatePicker, Button, Table, Select, TreeSelect, message } from 'antd'
import moment from 'moment'
import style from '../filingCaseManage/CaseManage.module.less'
const { Item } = Form
const { Option } = Select
const layout = {
  labelCol: { flex: '100px' }
}

// 获取表格字段配置
function getColumns () {
  return [
    {
      title: '序号',
      dataIndex: 'key',
      key: 'index',
      align: 'center',
      width: 60
    },
    {
      title: '名称',
      dataIndex: 'employee',
      key: 'employee',
      width: 100
    },
    {
      title: '在办',
      sorter: true,
      dataIndex: 'caseing',
      key: 'caseing',
      width: 110
    },
    {
      title: '已分配',
      sorter: true,
      dataIndex: 'caseon',
      key: 'caseon',
      width: 120
    },
    {
      title: '已分配结案',
      sorter: true,
      dataIndex: 'caseon_closure',
      key: 'caseon_closure',
      width: 180
    },
    {
      title: '结案',
      sorter: true,
      dataIndex: 'case_closure',
      key: 'case_closure',
      width: 110
    },
    {
      title: '结案平均审限',
      sorter: true,
      dataIndex: 'case_closure_avglimit',
      key: 'case_closure_avglimit',
      width: 180
    },
    {
      title: '已分配案由',
      dataIndex: 'caseon_cause_action',
      key: 'caseon_cause_action'
    }
  ]
}

class SecretaryStatistic extends Component {
  state = {
    dictionaries: {},
    causeActions: [],
    list: [],
    loading: false,
    orderField: '',
    order: ''
  }

  formRef = React.createRef()

  // 获取案由
  getCauseActions () {
    this.$get('/api/common/cause_action')
      .then(res => {
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          causeActions: res.data
        })
      })
  }

  // 获取枚举的字典值
  getDictionary () {
    this.$get('/api/xapc/dictionary', {
      types: '仲裁程序,结案类型'
    }).then(res => {
      if (res.status === 1) {
        // 设置枚举字典
        const dictionaries = this.formatDictionaries(res.data)
        this.setState({
          dictionaries
        })
      } else {
        message.error(res.message)
      }
    })
  }

  // 格式化枚举字典
  formatDictionaries (dictionaries = []) {
    const result = {}
    dictionaries.forEach(d => {
      result[d.type] = d.list
    })
    return result
  }

  // 格式化表单数据
  formatParams (form) {
    form = form || this.formRef.current.getFieldsValue()
    const { orderField, order } = this.state
    const params = { }
    const condition = []
    if (orderField && order) {
      params.order = order === 'ascend' ? 'asc' : 'desc'
      params.order_field = orderField
    }
    if (form.begintime) {
      params.begintime = Math.floor(form.begintime / 1000)
    }
    if (form.endtime) {
      params.endtime = Math.floor(form.endtime / 1000)
    }
    if (form.cause_action && form.cause_action.length) {
      condition.push({ k: 'cause_action', o: 'in', v: form.cause_action.join() })
    }
    if (form.procedure && form.procedure.length) {
      condition.push({ k: 'procedure', o: 'in', v: form.procedure.join() })
    }
    if (form.closure_type && form.closure_type.length) {
      condition.push({ k: 'closure_type', o: 'in', v: form.closure_type.join() })
    }
    params.condition = JSON.stringify(condition)
    return params
  }

  // 获取表格数据
  getTableData (form) {
    this.setState({ loading: true })
    this.$get('/api/xapc/casestat/statEmployeeCase', this.formatParams(form))
      .then(res => {
        this.setState({ loading: false })
        if (res.status !== 1) {
          return message.warning(res.message)
        }
        this.setState({
          list: res.data.map((li, i) => {
            li.key = i + 1
            return li
          })
        })
      }).catch(() => this.setState({ loading: false }))
  }

  // 表格请求变化
  tableChange (pagination, filters, sorter) {
    this.setState({
      orderField: sorter.field,
      order: sorter.order
    }, () => {
      this.getTableData()
    })
  }

  // 获取初始表单
  getInitialValues () {
    const year = moment().year()
    const date = moment(`${year}-01-01 00:00:00`)
    const begintime = moment(date)
    const endtime = moment(date)
    endtime.add(1, 'y')
    endtime.subtract(1, 's')
    return {
      begintime,
      endtime
    }
  }

  componentDidMount () {
    this.getCauseActions()
    this.getDictionary()
    this.getTableData()
  }

  render () {
    const { dictionaries } = this.state
    const procedureList = dictionaries['仲裁程序'] || []
    const closureList = dictionaries['结案类型'] || []
    const initialValues = this.getInitialValues()
    return (
      <div className={style.container}>
        <div className={style['title-line']}>
          <span>{this.props.title}</span>
        </div>
        <div className={style['search-container']}>
          <div className={style['search-form']}>
            <Form name='my_case_manage' {...layout} initialValues={initialValues} ref={this.formRef} onFinish={v => this.getTableData(v)}>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='起始日期' name='begintime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结束日期' name='endtime'>
                    <DatePicker className={style.full} placeholder='请选择日期' />
                  </Item>
                </Col>
                <Col span={8}>
                  <Item name='cause_action' label='案由'>
                    <TreeSelect
                      style={{ width: '100%' }}
                      dropdownStyle={{ maxHeight: 400, overflow: 'auto' }}
                      treeData={this.state.causeActions}
                      placeholder='请选择案由'
                      multiple
                      showSearch
                    />
                  </Item>
                </Col>
              </Row>
              <Row gutter={24}>
                <Col span={8}>
                  <Item label='仲裁程序' name='procedure'>
                    <Select style={{ width: '100%' }} placeholder='请选择仲裁程序' mode='multiple'>
                      {procedureList.map(li => (
                        <Option key={li.title} value={li.title}>{li.title}</Option>
                      ))}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item label='结案类型' name='closure_type'>
                    <Select style={{ width: '100%' }} placeholder='请选择结案类型' mode='multiple'>
                      {closureList.map(li => (
                        <Option key={li.title} value={li.title}>{li.title}</Option>
                      ))}
                    </Select>
                  </Item>
                </Col>
                <Col span={8}>
                  <Item>
                    <div className={style['search-btns']}>
                      <Button type='primary' ghost htmlType='submit'>搜索</Button>
                      <Button htmlType='reset' onClick={() => this.resetHandle()}>重置</Button>
                    </div>
                  </Item>
                </Col>
              </Row>
            </Form>
          </div>
        </div>
        <div className={style['table-container']}>
          <Table loading={this.state.loading} columns={getColumns.call(this)} dataSource={this.state.list} pagination={false} onChange={(...args) => this.tableChange(...args)} />
        </div>
      </div>
    )
  }
}

const mapState = mapStateToProps(function (state) {
  return {

  }
})

const mapDispatch = mapDispatchToProps(function (dispatch) {
  return {

  }
})

export default connect(mapState, mapDispatch)(SecretaryStatistic)
